#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <unistd.h>
#define N 10
using namespace std;

int tickets = 1000;

class ThreadArgv
{
public:
    ThreadArgv(mutex &lock)
        : lock_(lock)
    {
    }

    mutex &lock_;
    thread::id tid_;
};

class GrabTickets
{
public:
    typedef ThreadArgv argv;
    void operator()(argv _argv)
    {
        while (true)
        {
            // 使用 unique_lock 自动加锁和解锁
            unique_lock<mutex> lck(_argv.lock_);
            if (tickets == 0)
            {
                break;
            }
            tickets--;
            _argv.tid_ = this_thread::get_id();
            printf("票还剩%d,现在正在抢票的线程是", tickets);
            cout << _argv.tid_ << endl;
            usleep(500);
        }
    }
};

int main()
{
    mutex *lock = new mutex();
    vector<thread*> threadArr;
    for (int i = 0; i < N; i++)
    {
        ThreadArgv argv(*lock);
        thread *t = new thread(GrabTickets(),argv);
        threadArr.push_back(t);
    }

    for(auto &t:threadArr)
    {
        t->join();
        delete t;
    }
    
    delete lock;
    return 0;
}